import { Breadcrumb, type BreadcrumbProps } from "antd";
import {
  createContext,
  useContext,
  useMemo,
  useState,
  type PropsWithChildren,
} from "react";
import { Link, useMatches } from "react-router";

type BreadcrumbItem = (BreadcrumbProps["items"] & {})[number];

type DashboardBreadcrumbContext = {
  /** 进入 */
  push: (item: BreadcrumbItem) => void;
  /** 退出 */
  pop: () => void;
  /** 更新最后一个 */
  update: (item: BreadcrumbItem) => void;
};

const dashboardBreadcrumbContext = createContext(
  {} as DashboardBreadcrumbContext,
);

export function useDashboardBreadcrumbContext() {
  return useContext(dashboardBreadcrumbContext);
}

export default function DashboardBreadcrumbProvider({
  children,
}: PropsWithChildren) {
  const matches = useMatches();
  const [items, setItems] = useState<BreadcrumbItem[]>([]);

  const breadcrumbItems = useMemo(() => {
    const res = (
      matches
        .filter((match) => !!(match.handle as any)?.title)
        .map((match) => ({
          title: (match.handle as any).title,
          href: match.pathname,
        })) as BreadcrumbItem[]
    ).concat(items);

    const last = res[res.length - 1];
    if ("href" in last) {
      delete last.href;
    }

    return res;
  }, [matches, items]);

  const value = useMemo(() => {
    function push(item: BreadcrumbItem) {
      setItems((p) => [...p, item]);
    }
    function pop() {
      setItems((p) => p.slice(0, -1));
    }
    function update(item: BreadcrumbItem) {
      setItems((p) => (p.length ? p.slice(0, -1).concat(item) : p));
    }

    return { push, pop, update };
  }, []);

  return (
    <dashboardBreadcrumbContext.Provider value={value}>
      <Breadcrumb
        items={breadcrumbItems}
        itemRender={(route) =>
          route.href ? (
            <Link to={route.href}>{route.title}</Link>
          ) : (
            <span>{route.title}</span>
          )
        }
      />
      {children}
    </dashboardBreadcrumbContext.Provider>
  );
}
